package com.ruoyi.aitcommon.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;

public class JSONResult {
	public static JSONObject success() {
		return new JSONObject(AjaxResult.success());
	}
	public static JSONObject success(Object data) {
		return new JSONObject(AjaxResult.success(data));
	}
	public static JSONObject success(String msg) {
		return new JSONObject(AjaxResult.success(msg));
	}
	public static JSONObject success(String msg,Object data) {
		return new JSONObject(AjaxResult.success(msg, data));
	}
	public static JSONObject error() {
		return new JSONObject(AjaxResult.error());
	}
	public static JSONObject error(String msg) {
		return new JSONObject(AjaxResult.error(msg));
	}
	public static JSONObject error(String msg,Object data) {
		return new JSONObject(AjaxResult.error(msg,data));
	}
	public static JSONObject error(Exception ex){
		final String msg = ex.getMessage();
		// 获取堆栈跟踪元素数组
		final String trace = ExceptionUtils.getStackTraceAsString(ex);
		return new JSONObject(AjaxResult.error(msg, trace));
	}



	public static JSONObject jsonAssert(JSONObject json) throws Exception {
		if(json==null) throw new Exception("传入json为空");
		
		Integer code = json.getInteger(AjaxResult.CODE_TAG);
		if(code==null) {
			throw new Exception("参数json中的code为空");
		}else if(code==HttpStatus.ERROR_Repeat) {
			throw new AITException(code,json.getString(AjaxResult.MSG_TAG));
		}
		else if(code!=HttpStatus.SUCCESS) {
			throw new Exception(json.getString(AjaxResult.MSG_TAG));
		}else {
			return json;
		}
	}
	public static int getCode(JSONObject ret) {
		return ret.getIntValue(AjaxResult.CODE_TAG);
	}
	public static String getMsg(JSONObject ret) {
		return ret.getString(AjaxResult.MSG_TAG);
	}
	public static JSONObject getDataObject(JSONObject ret) {
		return ret.getJSONObject(AjaxResult.DATA_TAG);
	}
	public static JSONArray getDataArray(JSONObject ret) {
		return ret.getJSONArray(AjaxResult.DATA_TAG);
	}
	public static Object getData(JSONObject ret) {
		return ret.get(AjaxResult.DATA_TAG);
	}
	@SuppressWarnings("unchecked")
	public static List<Map<String,Object>> getDataListMap(JSONObject ret){
		List<Map<String,Object>> retlist=new ArrayList<Map<String,Object>>();
		JSONArray datalist=getDataArray(ret);
		
		for(Object item:datalist) {
			retlist.add((Map<String,Object>)item);
		}
		return retlist;
	}
	
	public static boolean isSuccess(JSONObject ret) {
		if(getCode(ret)==HttpStatus.SUCCESS)
			return true;
		else
			return false;
	}
	
	public static AjaxResult toAjaxResult(JSONObject ret) {
		AjaxResult ret1=new AjaxResult(getCode(ret),getMsg(ret),getData(ret));
		return ret1;
	}
	
}
